﻿using Microsoft.AspNetCore.Http;
using System.Security.Claims;

namespace QMERP.Infrastructure.Security
{
    public class CurrentUser : ICurrentUser
    {
        private static readonly Claim[] EmptyClaimsArray = Array.Empty<Claim>();
        private readonly ClaimsPrincipal _claimsPrincipal;
        public CurrentUser(IHttpContextAccessor httpContextAccessor)
        {
            _claimsPrincipal = (httpContextAccessor.HttpContext?.User ?? Thread.CurrentPrincipal as ClaimsPrincipal)!;
        }
        public long Id => _claimsPrincipal.FindUserId()!.Value;

        public string UserName => _claimsPrincipal.FindUserName()!;

        public string Name => _claimsPrincipal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)!.Value;

        public string? MobilePhone => _claimsPrincipal?.Claims?.FirstOrDefault(c => c.Type == ClaimTypes.MobilePhone)!.Value;

        public string? Email => _claimsPrincipal?.Claims?.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;

        public bool IsAdmin => Convert.ToBoolean(_claimsPrincipal?.Claims?.FirstOrDefault(c => c.Type == QMERPClaimTypes.IsAdmin)?.Value);

        public string[] Licenses => FindClaims(QMERPClaimTypes.Licenses).Select(c => c.Value).ToArray();

        public Claim? FindClaim(string claimType)
        {
            return _claimsPrincipal?.Claims?.FirstOrDefault(c => c.Type == claimType);
        }

        public Claim[] FindClaims(string claimType)
        {
            return _claimsPrincipal?.Claims?.Where(c => c.Type == claimType).ToArray() ?? EmptyClaimsArray;
        }

        public Claim[] GetAllClaims()
        {
            return _claimsPrincipal?.Claims?.ToArray() ?? EmptyClaimsArray;
        }
    }
}
